const connection = require("../config/mysql");

class UserService {
  async create(user) {
    const { name, password } = user;
    const statement =
    // uuid生成随机的数字，中间会有-分割，需要处理，使用replace() 函数处理
      "INSERT INTO `user` (id,name,password) VALUES (replace(uuid(),'-',''),?,?);";
      // "INSERT INTO `user` (name,password) VALUES (?,?);";
    // 返回的结果是一个数组，数组里面有两个小数组，values和fields，一般只需要values数据即可
    const [result] = await connection.execute(statement, [name, password]);
    return result;
  }

  // 查询数据库用户名
  async findUserName(name) {
    const statement = "SELECT * FROM `user` WHERE name = ?;";
    const [values] = await connection.execute(statement, [name]);
    return values;
  }

  async showAvatar(userId) {
    const statement = "SELECT * FROM avatar WHERE user_id = ?;"
    const [result] = await connection.execute(statement, [userId])
    try {
      return result.pop()
    } catch (error) {
      console.log(error);
    }
  }

  async updateUserAvatar(avatarUrl, userId) {
    const statement = "UPDATE user SET avatar_url = ? WHERE id = ?;"
    const [result] = await connection.execute(statement, [avatarUrl,userId])
    try {
      return result
    } catch (error) {
      console.log(err);
    }
  }
}

module.exports = new UserService();

